import random
from telnetlib import EC

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
import os
import re
import time
import json
import urllib
import urllib.request
import traceback
import string
from bs4 import BeautifulSoup
import jieba
import jieba.analyse

from sqlalchemy import Column, Integer, ForeignKey, String, create_engine, or_, Text, DateTime, Date, Time
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 读取json文件内容,返回字典格式
from test.ClipboardUtil import Clipboard
from pymouse import PyMouse
from pykeyboard import PyKeyboard

m = PyMouse()
k = PyKeyboard()


with open('./config.json', 'r',encoding='utf8')as fp:
    json_data = json.load(fp)
print(json_data)
# browser = webdriver.Chrome()
chrome_options = webdriver.ChromeOptions()

chrome_options.add_argument('--no-sandbox')  # 解决DevToolsActivePort文件不存在的报错
chrome_options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
# chrome_options.add_argument('--headless')  # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
browser = webdriver.Chrome("D:\\soft\\chromedriver", chrome_options=chrome_options)
browser.maximize_window()
wait = WebDriverWait(browser, 5)



class GetData:

    def __init__(self, url=''):
        self.text_name = "read_url.txt" # 继续读取未读的URL
        self.url = url
        self.video_num = -1
        self.dir_path = "file"
        self.root_path = ""
        self.num_thread = 10  # 默认线程
        self.timeout = 10  # 超时时间设置
        self.retry = 10  # 请求网页失败的最大重试次数
        self.cover_num = -1
        self.count = 0
        self.html = ''
        self.title = ''
        self.video_success = True
        self.wrong_ts_infor = ''
        self.wrong_pic_infor = ''
        self.pic_url_list = []
        self.ts_file_list = []
        self.final_fail_ts_file_list = []
        self.list_columns = ['xuhao', 'number', 'name', 'state', 'deadline', 'technologyNumber', 'productNumber', 'plannedQuantity', 'unit','plannedQuantityForAdditionalUnit',
                       'unitForAdditionalUnit','companyName','orderCategory','orderCategory1','orderCategory2','masterOrderNumber','masterOrderDefinitionNumber',
                        'workPlanDelivered','divisionName','isSubcontracted','annotation','existsRepairOrders']

    def right_url(self):
        if re.search(r'http://demo.cloudmes.io/\w+', self.url):
            return True
        else:
            print('url不正确')

    def should_pass(self, text_name):
        # self.video_num = re.search(r'https://kzx.360kan.com/(\w+)', self.url)
        self.video_num = self.url
        # print(self.video_num)
        if not os.path.exists(text_name):
            with open(text_name, mode='w', encoding='utf-8') as ff:
                print("文件创建成功！")
            return False
        else:
            with open(text_name, 'r') as f:
                for line in f:
                    if line[:-1] == self.video_num:
                        if text_name == 'SAVED.txt':
                            print('此视频已下载，跳过\n')
                        elif text_name == 'NO EXISTS.txt':
                            print('此视频不存在，跳过\n')
                        return True
                return False

    def filter_str(self, desstr, restr=''):
        import re
        # 过滤除中英文及数字以外的其他字符
        res = re.compile("[^\u4e00-\u9fa5^a-z^A-Z^0-9]")
        return res.sub(restr, desstr)

    def download_file(self, title, ts_url):
        # print(ts_url)
        if len(title) <= 30:
            newtitle = title
        else:
            newtitle = self.filter_str(title)
            if len(newtitle) > 30:
                newtitle = newtitle[0:-29]
        try:
            urllib.request.urlretrieve(ts_url, self.dir_path + '/%s.mp4' % (newtitle))
            print('%s , %s下载成功' % (title, ts_url))
            self.write(title, url)
        except Exception as e:
            print(f"Unexpected error: {e}")

    def write(self, title, url):
        file_path = os.path.join(self.root_path, 'record.txt')
        with open(file_path, 'a', encoding='utf-8') as f:
            f.write('标题：\n%s\n网址：\n%s\n' % (title, url))

    def readurl(self):
        if os.path.exists(self.text_name):
            with open(self.text_name, 'r', encoding='utf-8') as f:
                self.url = f.read()
        return self.url

    def fenci(self, text):
        # fenci_text = jieba.cut( text )
        print('fenci')
        # print("/ ".join(fenci_text))

        # 第二步：去停用词
        # 这里是有一个文件存放要改的文章，一个文件存放停用表，然后和停用表里的词比较，一样的就删掉，最后把结果存放在一个文件中
        # stopwords = {}.fromkeys( [line.rstrip() for line in open( 'stopwords.txt' )] )
        # final = ""
        # for word in fenci_text:
        #     if word not in stopwords:
        #         if (word != "。" and word != "，"):
        #             final = final + " " + word
        # print( final )

        # 第三步：提取关键词
        a = jieba.analyse.extract_tags(text, topK=5, withWeight=True, allowPOS=())
        b = jieba.analyse.extract_tags(text, topK=6, allowPOS=())
        print(a, b)
        return b



    def newurl(self):
        browser.get(self.url)
        time.sleep(10)
        bsObj = BeautifulSoup(browser.page_source, 'html.parser')
        urls = bsObj.findAll('a', attrs={'href': re.compile("^/v\?vid")})
        try:
            newurl = '{}{}'.format(self.url.split('/v')[0], random.choice(urls).get('href'))
            with open(self.text_name, 'w', encoding='utf-8') as f:
                f.write(newurl)
        except Exception as e:
            print(f"Unexpected error: {e}")

    def download(self,user,ik3cloud):
        current_window_old = []
        url = self.readurl()
        browser.get(url)
        browser.implicitly_wait( 5 ) # 隐性等待和显性等待可以同时用，但要注意：等待的最长时间取两者之中的大者
        btn_login = browser.find_element_by_class_name('header-user-content').find_element_by_class_name('btn-login')
        btn_login.click()
        browser.implicitly_wait( 5 )
        # 进入下一级页面
        current_window = browser.current_window_handle  # 获取当前窗口handle name
        all_window = browser.window_handles
        for window in all_window:
            if window != current_window:
                browser.switch_to.window( window )
        current_window = browser.current_window_handle  # 获取当前窗口handle name
        current_window_old.append( current_window )

        username_login = browser.find_element_by_id('tellName')
        password_login = browser.find_element_by_class_name('login_input_passwrod')
        unselectable = browser.find_element_by_class_name( 'unselectable' )
        unselectable.click()
        username_login.send_keys(user['username'])
        password_login.send_keys(user['password'])
        login_button = browser.find_element_by_class_name('loginBtn')

        current_window = browser.current_window_handle  # 获取当前窗口handle name
        current_window_old.append(current_window)
        login_button.click()
        browser.implicitly_wait( 5 )
        # 进入下一级页面

        # bsObj = BeautifulSoup( browser.page_source, 'html.parser' )
        jieshou_button = browser.find_element_by_xpath('//*[@id="app"]/div/div[1]/div[1]/div/div/div[3]/div/div[3]/button/span')
        if jieshou_button:
            jieshou_button.click()
            browser.implicitly_wait( 5 )
        # 进入 全能用户
        PracticeCenter_url = ik3cloud['PracticeCenter']
        browser.get(PracticeCenter_url)
        browser.implicitly_wait( 10 )
        current_window = browser.current_window_handle  # 获取当前窗口handle name
        current_window_old.append(current_window)
        # 显性等待
        try:
            element = WebDriverWait(browser, 20).until(lambda x: x.find_element_by_link_text("全能用户"))
        except OSError as e:
            print( e )
            browser.close()
            return
        quanneng_button = browser.find_element_by_link_text( '全能用户' )
        quanneng_button.click()
        # time.sleep( 10 )
        browser.implicitly_wait( 15 )
        all_window = browser.window_handles
        for window in all_window:
            if window != current_window:
                browser.switch_to.window( window )
        current_window = browser.current_window_handle  # 获取当前窗口handle name
        current_window_old.append( current_window )
        # time.sleep(10)
        browser.implicitly_wait( 30 )
        try:
            element = WebDriverWait( browser, 30 ).until(lambda x: x.find_element_by_class_name( "kd_SystemMenu" ) )
            element.click()
            # time.sleep(10)
            browser.implicitly_wait( 20 )
        except OSError as e:
            print(e)
            browser.close()
            return

        # 供应链 》 库存管理 》 采购入库单
        try:
            element = WebDriverWait( browser, 30 ).until(lambda x: x.find_element_by_xpath( '//*[@id="parentli_Top20"]/div/div') )
            element.click()
            # time.sleep(5)
            browser.implicitly_wait( 5 )
        except Exception as e:
            print(e)
            browser.close()
            return
        if browser.find_element_by_xpath('//*[@id="childnavli_21"]/div/div').text != '':
            browser.find_element_by_xpath('//*[@id="childnavli_21"]/div/div').click()
            # time.sleep(5)
            browser.implicitly_wait( 5 )
        else:
            browser.find_element_by_xpath( '//*[@id="parentli_Top20"]/div/div' ).click()
            browser.implicitly_wait( 5 )
            browser.find_element_by_xpath( '//*[@id="childnavli_21"]/div/div' ).click()
            browser.implicitly_wait( 5 )
        try:
            element = WebDriverWait( browser, 60 ).until(lambda x: x.find_element_by_css_selector('#BOS_MainSystemMenuCard-KDINFOLINK573C0A2B7515CF_c') )
            element.click()
            browser.implicitly_wait( 10 )
        except Exception as e:
            print(e)
            browser.close()
            return

        # 进入下一级页面
        # all_window = browser.window_handles
        # for window in all_window:
        #     if window != current_window:
        #         browser.switch_to.window(window)
        # current_window = browser.current_window_handle  # 获取当前窗口handle name
        # current_window_old.append(current_window)
        # 进入 采购入库单 新增页面
        try:
            element = WebDriverWait( browser, 20 ).until(lambda x: x.find_elements_by_tag_name('tbody') )
        except Exception as e:
            print(e)
            browser.close()
            return
        bsObj = BeautifulSoup( browser.page_source, 'html.parser')

        # 选择组织 101.1  蓝海柴油机本部
        try:
            element = WebDriverWait(browser, 30 ).until( lambda x: x.find_element_by_xpath('//*[@id="6c58621d-b939-4583-b96a-6cb61622eb68-FBTNORG"]') )
            element.click()
            time.sleep(1)
            element = WebDriverWait(browser, 30).until(
                lambda x: x.find_element_by_css_selector('body > div.k-animation-container > ul > li:nth-child(3)'))
            element.click()
            time.sleep(1)
        except Exception as e:
            print(e)
            browser.close()
            return

        #  填写数据
        td_list = browser.find_elements_by_tag_name( 'tbody' )[0].find_elements_by_tag_name( 'tr' )[0].find_elements_by_tag_name('td')

        for i in td_list:
            # 物料编码
            if i.find_element_by_tag_name('span').get_attribute('data-field') == 'FMATERIALID':
                print('物料编码')
                i.click()
                # 调用setText设置剪贴板内容
                # Clipboard.setText("000001.2000")
                # Clipboard.getText()
                # # 模拟键盘组合键Ctrl+v将剪贴板的内容复制到搜索输入框中
                # k.press_key(k.control_key)
                # k.tap_key('v')
                # 松开键
                # k.release_key( k.control_key )
                for k in list('000001.2000'):
                    k.tap_key(k)
                time.sleep(2)
            if i.get_attribute('data-role') and i.find_element_by_tag_name('input'):
                if i.find_element_by_tag_name('input').get_attribute('class') == 'kd-editor-input-bound':
                    print('实收数量')
                    i.send_keys('100')
            if i.get_attribute('data-role') == 'editable':
                if i.find_element_by_tag_name( 'div' ).get_attribute( 'data-field' ) == 'FSTOCKID':
                    print('仓库')
                    i.click()
                    i.send_keys('0')


        # # 库存单位
        # browser.find_element_by_xpath(
        #     '//*[@id="da4b7fa6-61de-4861-8330-f9d2b4dcd0a7-FINSTOCKENTRY_FUNITID"]/span/span/span[2]' )
        # # 实收数量
        # browser.find_element_by_xpath(
        #     '//*[@id="da4b7fa6-61de-4861-8330-f9d2b4dcd0a7-FINSTOCKENTRY-c"]/div[2]/table/tbody/tr/td[26]/span' )
        # # 仓库
        # browser.find_element_by_xpath(
        #     '//*[@id="da4b7fa6-61de-4861-8330-f9d2b4dcd0a7-FINSTOCKENTRY-c"]/div[2]/table/tbody/tr/td[31]/div/span')


        # 选中ifrem
        # browser.switch_to_frame(0)
        # 选中td,然后点击td
        # row = browser.find_elements_by_class_name('jqgrow')
        # ids = []
        # rows = []
        # ordersList_url = browser.current_url
        #
        # for i in row:
        #     # id = i.get_attribute("id")
        #     ids.append(i.get_attribute("id"))
        #     td_text = []
        #     td_text.append(i.get_attribute("id"))
        #     for j in range(len(i.find_elements_by_tag_name('td'))):
        #         if j>0:
        #             td_text.append(i.find_elements_by_tag_name('td')[j].text.strip())
        #     rows.append(dict(zip(self.list_columns,td_text)))
        # print(rows)
        # self.add_order(rows)
        # # 写文件
        # with open('./rows.json', 'w', encoding = 'utf8')as fp:
        #     fp.write(json.dumps(rows))


if __name__ == '__main__':
    # url = input('请输入网址：\n')
    count = 1000
    start = time.perf_counter()
    url = json_data[0]['ik3cloud']['url']
    ik3cloud = json_data[0]['ik3cloud']
    users = json_data[0]['ik3cloud']['users'][0]
    Get_Data = GetData(url)
    Get_Data.download(users,ik3cloud)
    time.sleep(10)
    end = time.perf_counter()
    print('任务执行共%d小时%d分%.2f秒,' % ((end - start) // 3600, (end - start) % 3600 // 60, (end - start) % 60))
    browser.quit()